<template>
  <micro-app
    v-if="app && app.name && app.url && !loadError"
    @created="handleCreate"
    @beforemount="handleBeforeMount"
    @mounted="handleMount"
    @unmount="handleUnmount"
    @error="handleError"
    @datachange="handleDataChange"
    @beforeshow="beforeshow"
    @aftershow="aftershow"
    v-bind.camel="app"
    :keep-alive="app.keepAlive"
    :router-mode="app.routerMode"
    :baseroute="app.baseroute || app.name"
    :data="app.data"
    inline
    keep-router-state
  />
  <div v-else-if="loadError">
    <a-card :bordered="false">
      <a-result status="error" :title="`微应用【${app?.name}】加载错误`" :sub-title="` 请确定微应用服务是否已启动。`">
        <template #extra>
          <a-button type="primary" @click="() => router.push('/')">返回首页</a-button>
        </template>
        <div>
          <div>{{ loadError?.detail.error }}</div>
          <div>{{ loadError?.detail.error.stack }}</div>
        </div>
      </a-result>
    </a-card>
  </div>
  <div v-else>
    <a-card :bordered="false">
      <a-result status="error" title="加载失败" :sub-title="`微应用【${route.path}】未配置`">
        <template #extra>
          <a-button type="primary" @click="() => router.push('/config/app-config')">前往配置</a-button>
        </template>
      </a-result>
    </a-card>
  </div>
</template>

<script lang="ts" setup name="hs-micro-app">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import microApp from '@micro-zoe/micro-app';

  const route = useRoute();
  const router = useRouter();
  const apConfig = [
    {
      id: '1000000',
      name: 'zeroing',
      url: 'https://zeroing.jd.com/micro-app/vue3', //   iframe: true,
      baseroute: '/zeroing/',
      iframe: true,
      routerMode: 'native',
      keepAlive: true,
    },
    {
      id: '1000002',
      name: 'pzgl',
      url: 'https://fxhs-demo.jchl.com/fxhs-jsgl-web/',
      baseroute: '/pzgl/',
      iframe: true,
      routerMode: 'native',
      keepAlive: true,
    },
    {
      id: '1000003',
      name: 'fx-report',
      url: '/foreseereport-web/',
      baseroute: '/fx-report/',
      iframe: true,
      routerMode: 'native',
      keepAlive: true,
    },
    {
      id: '1000004',
      name: 'fxgl',
      url: 'https://fxhs-demo.jchl.com/fxgl/',
      baseroute: '/fxgl/',
      iframe: true,
      routerMode: 'native',
      keepAlive: true,
    },
    {
      id: '1000005',
      name: 'fk-base',
      url: 'http://10.10.145.98:32417',
      baseroute: '/fk-base',
      iframe: true,
      routerMode: 'native',
      keepAlive: true,
    },
  ];
  const loadError = ref<{ detail: { error: Error } }>();

  const app = computed(() => {
    try {
      const app = apConfigGetByUrl(route.path);
      //console.log('--------> ', route.path, app, apConfigStore);
      const routeQuery = route.query;
      app!.data = {
        routeQuery,
      };
      return app;
    } catch (e) {
      // throw new Error(`微应用【${route.path}】未找到。`)
      return null;
    }
  });

  const apConfigGetByUrl = (url: string) => {
    let [basePath] = url.replace(/^\/+/, '').split('/');
    let appInfo = apConfig.find((item) => {
      if (item.baseroute === `/${basePath}/`) {
        return item;
      }
    });
    return appInfo || {};
  };

  onMounted(() => {
    console.log(`---------->>> ${app.value?.name} 创建了`, 'onMounted: ', app);
  });

  const handleCreate = () => {
    console.log(`${app.value?.name} 创建了`, app);
  };

  const handleBeforeMount = () => {
    console.log(`${app.value?.name} 即将被渲染`);
  };

  const handleMount = () => {
    console.log(`${app.value?.name} 已经渲染完成`);
  };

  const handleUnmount = () => {
    console.log(`${app.value?.name} 卸载了`);
  };

  const handleError = (e: any) => {
    loadError.value = e;
    console.log(`${app.value?.name} 加载出错了`);
  };

  const handleDataChange = (e: CustomEvent): void => {
    console.log(`${app.value?.name} 的数据`, e.detail.data);
  };
  const beforeshow = () => {
    console.log(`${app.value?.name} 即将推入前台，初始化时不执行`);
  };
  const aftershow = () => {
    console.log(`${app.value?.name} 已经推入前台，初始化时不执行`, app.value!.name, app.value, route);
    microApp.router.replace({ name: app.value!.name, path: route.fullPath });
  };
  //   }
  // }
</script>

<style lang="less" scoped>
  .main-content {
    background: linear-gradient(0deg, #f5f5f5, #f5f5f5), #ffffff;
  }
</style>
